(ns admin-framework.transaction
  (:gen-class
   :extends org.jboss.netty.channel.SimpleChannelHandler
   :init init
   :state authenticated)
  (:use [cheshire.core]
        [cheshire.factory]
        admin-framework.work)
  (:require [clojure.contrib.sql :as sql])
  (:import org.jboss.netty.channel.SimpleChannelHandler))

(defn -init []
  [[] (atom false)])

(defn get-buf-str [buf]
  (.toString buf (java.nio.charset.Charset/forName "UTF-8")))

(defn auth
  ([this] @(.authenticated this))
  ([this name pwd]
     (login name pwd)))

(defmulti call-rpc (fn [this ch jsdata & arg] (jsdata "id")))

;;login
(defmethod call-rpc 1 [this ch jsdata]
  (println "this is 1"))

(defmethod call-rpc 2 [this ch jsdata]
  (println "this is 2"))

(defn -messageReceived [ctx msg]
  (let [buf (.getMessage msg)
        utf (get-buf-str [buf])
        data (parse-string utf)]
    (call-rpc data)))

(defn get-buf-str [buf]
  (.toString buf (java.nio.charset.Charset/forName "UTF-8")))

(defn -messageReceived [this ctx msg]
   (let [buf (.getMessage msg)
         utf  (get-buf-str buf)
         ch (.getChannel msg)
         data (parse-string utf)]
     (if-not (auth this "zdc" "e10adc3949ba59abbe56e057f20f883e")
       (.write ch (generate-string {:id 1, :name "hello"}))
       (call-rpc this ch data))))

(defn -exceptionCaught [this ctx e]
  (println "catch exception" e))

(defn -channelClosed [this ctx e]
  (println "Channel closed" e))

(defn -channelConnected [this ctx e]
  (println "Channel connected" e))
